package JavaCollection.mapLearn;



import org.junit.jupiter.api.Test;

import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;

/**
 * @author Lenl
 * @version v1.0
 * @create 2021-06-05 14:51
 * @description
 */
public class TreeMapTest {
    //向TreeMap添加元素要求key必须是由同一类创建的对象
    //因为要按照key进行排序：自然排序、定制排序

    @Test
    public void test1(){
        TreeMap map=new TreeMap();//这里放入参数则为定制排序
        Users u1=new Users("java",21);
        Users u2=new Users("C#",22);
        Users u3=new Users("Go",23);
        Users u4=new Users("javeop",26);
        map.put(u1,98);
        map.put(u2,98);
        map.put(u3,86);
        map.put(u4,60);

        Set set=map.entrySet();
        for (var x:set){
            System.out.println(x);
        }

    }

}
class Users implements Comparable{
    private String name;
    private int age;

    public Users() {
    }

    public Users(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Users user = (Users) o;
        return age == user.age &&
                Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {
        int result=name!=null?name.hashCode():0;
        result=31*result+age;
        return result;
    }

    @Override
    public int compareTo(Object o) {
        //按姓名从小到大排 年龄从小到大排
        if(o instanceof Users){
            Users u=(Users)o;
            int compare= this.name.compareTo(u.name);
            if(compare!=0) return compare;
            else return Integer.compare(this.age,u.age);
        }else{
            throw  new RuntimeException("输入类型不匹配");
        }
    }
}